﻿using System.Windows;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;

namespace DiagramDesigner.Common.Adorners
{
    public class RectangularSelectionAdorner : Adorner
    {
        private Point _startPoint;
        private Point _endPoint;
        private UIElement _canvas;
        private Pen _pen;

        public RectangularSelectionAdorner(UIElement canvas, Point startPoint) : base(canvas)
        {
            _startPoint = startPoint;
            _canvas = canvas;
            _pen = new Pen(Brushes.Black, 1);
            _pen.DashStyle = new DashStyle(new DoubleCollection { 4,4 }, 0);
        }

        protected override void OnMouseMove(System.Windows.Input.MouseEventArgs e)
        {
            
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                if (!IsMouseCaptured) CaptureMouse();    
                _endPoint = e.GetPosition(_canvas);
                InvalidateVisual();
            }
            else
            {
                if (this.IsMouseCaptured) this.ReleaseMouseCapture();
            }

            e.Handled = true;
        }

        protected override void OnMouseLeftButtonUp(System.Windows.Input.MouseButtonEventArgs e)
        {
            if (IsMouseCaptured) ReleaseMouseCapture();
            AdornerLayer.GetAdornerLayer(_canvas).Remove(this);
            e.Handled = true;
        }

        protected override void OnRender(System.Windows.Media.DrawingContext dc)
        {
            base.OnRender(dc);
            dc.DrawRectangle(Brushes.Transparent, null, new Rect(RenderSize));
            dc.DrawRectangle(null, _pen, new Rect(_startPoint, _endPoint));
        }
    }
}
